<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Konva</title>
		<script src="https://unpkg.com/konva@7.0.3/konva.min.js"></script>
  </head>
  <body>
    <div id="container"></div>
		<!-- Knova官网 https://konvajs.github.io/ -->
    <script>
      // 创建舞台
      var stage = new Konva.Stage({
      	container: 'container',
      	width: window.innerWidth,
      	height: window.innerHeight
      })
      
      // 创建层
      var layer = new Konva.Layer()
      stage.add(layer)
      
      // 中心点坐标
      var cenX = stage.width() / 2
      var cenY = stage.height() / 2
			
			// 饼状图的数据
			var data = [
				{ name:'Web', value: '.25', color: 'green'},
				{ name:'PHP', value: '.1', color: 'blue'},
				{ name:'Java', value: '.2', color: 'red'},
				{ name:'UI', value: '.05', color: 'orange'}, 
				{ name:'IOS', value: '.2', color: 'purple'},
				{ name:'Android', value:'.2', color:'pink'}
			];
			
			// 做一个扇形
			var x0 = cenX;
			var y0 = cenY;
			var tempAngle = -90;
			data.forEach(function(item,index){
				var angle = item.value * 360;
				var wedge = new Konva.Wedge({
					x: x0,
					y: y0,
					angle: angle,
					radius: 100,
					fill: item.color,
					rotation: tempAngle,
					name: 'wedge'
				});
				layer.add(wedge);
				
				// 添加百分比文字
				var textAngle = tempAngle + 1/2 * angle;
				var text = new Konva.Text({
					x: x0 + (100+20) * Math.cos(Math.PI / 180 * textAngle),
					y: y0 + (100+20) * Math.sin(Math.PI / 180 * textAngle),
					text: item.value * 100 + '%',
					fill: item.color
				});
				if(textAngle > 90 && textAngle < 270){
					text.x(text.x() - text.getWidth());
				}
				layer.add(text);
				
				tempAngle += angle
			})
			
			var circle = new Konva.Circle({
				x: x0,
				y: y0,
				radius: 110,
				stroke: '#ccc',
				strokeWidth: 2,
			})
			layer.add(circle);
			
			layer.draw();
			
			// 绘制动画
			var index = 0;
			var wedges = layer.find('.wedge');
			wedges.each(function(item,index){
				item.angle(0);
			})
			function animatePie(){
				var item = wedges[index];
				item.to({
					angle: data[index].value * 360,
					duration: data[index].value * 2,
					onFinish: function(){
						index++;
						if(index >= data.length){
							return;// 立即结束当前函数
						}
						animatePie()
					}
				})
			}
			animatePie()
    </script>
  </body>
</html>